package com.atguigu.chapter07.state;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/15 14:02
 */
public class Flink06_State_Key_Aggregate {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment
            .getExecutionEnvironment()
            .setParallelism(1);
        env
            .socketTextStream("hadoop162", 9999)
            .map(value -> {
                String[] datas = value.split(",");
                return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
                
            })
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
    
                private AggregatingState<Integer, Double> avgState;
    
                class Avg {
                    public Integer sum = 0;
                    public Long count = 0L;
                    
                    public Double get(){
                        return sum * 1.0 / count;
                    }
                }
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    avgState = getRuntimeContext().getAggregatingState(new AggregatingStateDescriptor<Integer, Avg, Double>(
                        "avgState",
                        new AggregateFunction<Integer, Avg, Double>() {
                            @Override
                            public Avg createAccumulator() {
                                return new Avg();
                            }
        
                            @Override
                            public Avg add(Integer value, Avg acc) {
                                acc.sum += value;
                                acc.count ++;
                                return acc;
                            }
        
                            @Override
                            public Double getResult(Avg acc) {
                                return acc.get();
                            }
        
                            @Override
                            public Avg merge(Avg a, Avg b) {
                                return null;
                            }
                        },
                        Avg.class));
                }
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    avgState.add(value.getVc());
                    
                    out.collect(ctx.getCurrentKey() + " " + avgState.get());
                }
            })
            .print();
        
        env.execute();
        
    }
}
